package com.hb.trade.api.routine.controller.project.proj;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.hb.core.pojo.RoleDataAuthEntity;
import com.hb.core.pojo.center.au.entity.Org;
import com.hb.core.pojo.center.sys.entity.DicCode;
import com.hb.core.pojo.center.sys.entity.DistrictInfo;
import com.hb.core.pojo.enums.ProjectTypeEnum;
import com.hb.core.pojo.parent.PageResult;
import com.hb.core.pojo.project.proj.dto.InquiryProjectThanDTO;
import com.hb.core.pojo.project.proj.entity.AbstractProject;
import com.hb.core.pojo.project.proj.entity.QueryProject;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.trade.api.routine.service.BidSectionService;
import com.hb.trade.api.routine.util.RoleDataAuthUtil;
import com.hb.trade.client.center.DictionaryClient;
import com.hb.trade.client.center.OrgClient;
import com.hb.trade.client.center.OrgDeptClient;
import com.hb.trade.client.center.RoleClient;
import com.hb.trade.client.project.ProjectClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.auth.shiro.util.ShiroUtil;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.model.msg.ResponseDto;
import org.fzzn.core.util.Enums;
import org.fzzn.core.util.ResultUtil;
import org.fzzn.core.web.anno.Version;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

/**
 * 项目信息业务模块接口
 * 主要包含项目信息的增删改查以及项目其他信息的维护
 *
 * @author zhongdl
 * @since 2021/12/01
 */
@Slf4j
@Version(1.0)
@Api(tags = {"项目相关的"})
@RequestMapping("/{version}")
@RestController
public class ApiProjectController {

    protected final OrgDeptClient orgDeptClient;
    protected final OrgClient orgClient;
    protected final RoleClient roleClient;
    protected final BidSectionService bidSectionService;
    protected final ProjectClient projectClient;
    protected final DictionaryClient dictionaryClient;

    public ApiProjectController(OrgDeptClient orgDeptClient,
                                OrgClient orgClient,
                                RoleClient roleClient,
                                BidSectionService bidSectionService,
                                ProjectClient projectClient,
                                DictionaryClient dictionaryClient) {
        this.orgDeptClient = orgDeptClient;
        this.orgClient = orgClient;
        this.roleClient = roleClient;
        this.bidSectionService = bidSectionService;
        this.projectClient = projectClient;
        this.dictionaryClient = dictionaryClient;
    }

    /**
     * 新增项目信息
     *
     * @param projectJSON 项目参数使用JSONObject来接收, 可以处理多种项目类型使用同一个新建项目接口
     * @return 接口响应对象
     * @update zhaojk
     * @see InquiryProjectThanDTO
     */
    @ApiOperation(value = "新增项目信息", notes = "新增项目信息, 用于不走工作流直接新增状态为审核通过的项目")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "项目ID", dataTypeClass = String.class), @ApiImplicitParam(name = "bidWay", value = "项目类型枚举(1:招标,2:竞争性磋商,3:竞争性谈判,4:询比价,5:单一来源采购,6:直接采购,7:询价,8:竞价 )", dataTypeClass = Integer.class), @ApiImplicitParam(name = "projectModule", value = "项目模块 1 建设工程 2 政府采购 3 企业采购", dataTypeClass = Integer.class, required = true),

            @ApiImplicitParam(name = "registrationFeeMoney", value = "报名费金额", dataTypeClass = BigDecimal.class), @ApiImplicitParam(name = "systemUseFee", value = "系统使用费金额", dataTypeClass = BigDecimal.class),

            @ApiImplicitParam(name = "sections[0].signUpCollectionId", value = "报名费收款方式ID", dataTypeClass = Long.class), @ApiImplicitParam(name = "sections[0].sysCollectionId", value = "系统使用费收款方式ID", dataTypeClass = Long.class)})
    @PostMapping("/project/newProject")
    public ResponseDto pageUsers(@RequestBody JSONObject projectJSON) {
        //企业id
        projectJSON.putOpt("orgId", ShiroUtil.getExtInfo(Org.class).getId());
        //用户id
        projectJSON.putOpt("userId", ShiroUtil.getUserId());
        Message<Boolean> message = projectClient.newProject(projectJSON);
        if (message.isSuccess()) {
            return ResultUtil.success(message.getMessage());
        }
        return ResultUtil.fail(message.getMessage());
    }

    /**
     * @param project: 查询项目的参数
     * @Description: 项目列表信息接口
     * @Author: zhongdl
     * @Date:2021/12/2 10:45
     * @return: org.fzzn.core.model.msg.Message<com.hb.core.pojo.parent.PageResult < cn.hutool.json.JSONObject>>
     **/
    @ApiOperation(value = "项目列表信息", notes = "项目列表信息(带标段信息)")
    @PostMapping("/project/projects")
    public ResponseDto<?> projects(@RequestBody QueryProject project) {
        // 设置数据权限, 添加数据权限条件
        RoleDataAuthEntity authEntity = RoleDataAuthUtil.buildDataAuth();
        project.setDataAuth(authEntity);
        // 项目类型, 该字段必填
        if (project.getProjectModule() == null) {
            return ResultUtil.fail("项目模块字段必传");
        }
        Message<PageResult<AbstractProject>> projects = projectClient.projects(project);
        if (projects.isSuccess()) {
            // 设置标段状态显示列表 start
            PageResult<AbstractProject> data = projects.getData();
            for (AbstractProject record : data.getRecords()) {
                List<BidSectionDTO> sections = record.getSections();
                List<BidSectionDTO> newSections = bidSectionService.displaySectionStatuses(sections);
                record.setSections(newSections);
            }
            // 设置标段状态显示列表 end
            return ResultUtil.msg(true, data);
        }
        return ResultUtil.fail(projects.getMessage());
    }

    /**
     * @Description: 获取指定项目的详情
     * @Author: zhongdl
     * @Date:2021/12/2 16:50
     * @return: {@link ResponseDto }
     **/
    @ApiOperation(value = "获取指定项目的详情", notes = "获取指定项目的详情")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "项目ID", dataTypeClass = String.class), @ApiImplicitParam(name = "bidWay", value = "项目类型枚举", dataTypeClass = Integer.class), @ApiImplicitParam(name = "projectModule", value = "项目模块 1 建设工程 2 政府采购 3 企业采购", dataTypeClass = Integer.class), @ApiImplicitParam(name = "withSections", value = "项目详情是否查询标段信息(true: 返回标段列表)", dataTypeClass = Integer.class)})
    @PostMapping("/project/detail")
    public ResponseDto projectDetail(@RequestBody AbstractProject project) {
        Message<AbstractProject> abstractProjectMessage = projectClient.projectDetail(project);
        if (abstractProjectMessage.isFail()) {
            return ResultUtil.fail(abstractProjectMessage.getMessage());
        }
        //设置字典值
        AbstractProject data = abstractProjectMessage.getData();
        if (BeanUtil.isEmpty(data)) {
            return ResultUtil.fail(MsgEnum.FAILURE);
        }
        log.info(">>>>>>>>>>>data数据为" + data);
        DistrictInfo areaInfo = StrUtil.isEmpty(data.getArea()) ? new DistrictInfo() : dictionaryClient.districtsById(data.getArea());
        DistrictInfo cityInfo = StrUtil.isEmpty(data.getCity()) ? new DistrictInfo() : dictionaryClient.districtsById(data.getCity());
        DistrictInfo provinceInfo = dictionaryClient.districtsById(data.getProvince());
        data.setAreaName(areaInfo.getDisName());
        data.setCityName(cityInfo.getDisName());
        data.setProvinceName(provinceInfo.getDisName());
        // 查询行业分类
        Message<DicCode> dicCodeMessage = dictionaryClient.selectDicCodeByTypeCodeAndDicLabel("hangyeleibie", data.getIndustryType());

        if (dicCodeMessage.isSuccess() && null != dicCodeMessage.getData()) {
            data.setIndustryTypeName(dicCodeMessage.getData().getDicValue());
        }
        data.setProjectTypeName(Enums.nameOf(ProjectTypeEnum.class, data.getProjectType()));
        return ResultUtil.msg(true, data);
    }

    /**
     * @param projectJSON:
     * @Description: 更新发起流程的项目信息
     * @Author: zhongdl
     * @Date:2021/12/2 16:59
     * @return: {@link ResponseDto }
     **/
    @ApiOperation(value = "更新发起流程的项目信息", notes = "更新发起流程的项目信息, 用于发起工作流之后完善项目信息的自定义更新项目接口")
    @PostMapping("/project/update")
    public ResponseDto updateNewProject(@RequestBody JSONObject projectJSON) {
        Message<Boolean> message = projectClient.updateNewProject(projectJSON);
        if (message.isSuccess()) {
            return ResultUtil.success(message.getMessage());
        }

        return ResultUtil.fail(message.getMessage());
    }

    @ApiOperation(value = "删除项目", notes = "项目列表中删除项目，根据项目ID进行伪删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "项目ID", dataTypeClass = Long.class)})
    @PostMapping("/project/deleteProjectById")
    public ResponseDto deleteProjectById(@RequestBody AbstractProject abstractProject) {
        if (abstractProject == null || abstractProject.getId() == null) {
            return ResultUtil.fail(MsgEnum.INCORRECT_PARAM.msg());
        }
        Message message = this.projectClient.deleteProjectById(abstractProject);
        return ResultUtil.msg(message);
    }
}
